from time import sleep
from playwright.sync_api import Page, BrowserContext

from model.ProConfModel import ProConfModel
from tools.Result import error_result, success_result
from tools.HtmlPageService import get_selector_src
from tools.Ocr import get_by_base64
# 全局存储响应数据（可根据需求调整）
is_login_success =False
def handle_response(response):
    """响应处理器（带数据收集功能）"""
    global is_login_success
    # 记录所有响应URL
    if "loginPre" in response.url:
        response_data = response.json()
        if (response_data.get("code") == 200):
            is_login_success = True



def login_with_validate_code(
    page: Page,
    context:BrowserContext,
    pro_conf: ProConfModel
) -> bool:
    global is_login_success
    is_login_success = False
    page.on("response", handle_response)
    page.wait_for_timeout(300)  # 简单延迟，确保响应已捕获
    for i in range(3):
        do_login(page, pro_conf)
        page.wait_for_timeout(500)
        if is_login_success:
            return True
    # 等待登录接口响应
    page.wait_for_timeout(100)  # 简单延迟，确保响应已捕获

    return is_login_success


def do_login( page: Page,   pro_conf: ProConfModel):

    """执行带滑块验证的登录，并返回登录接口的 JSON 数据"""
    page.goto(pro_conf.login_url, wait_until="load", timeout=15000)
    page.get_by_text("登录", exact=True).click()
    page.get_by_role("textbox", name="请输入账号").fill(pro_conf.login_name)
    page.get_by_role("textbox", name="请输入密码").fill(pro_conf.login_password)
    sleep(0.5)
    page.wait_for_selector(".img-code-box > img", state="visible")
    base64_str = get_selector_src(page, ".img-code-box > img")

    validate_code = get_by_base64(base64_str)

    page.get_by_role("textbox", name="请输入图形验证码").fill(validate_code)

    page.locator(".sub-btn").get_by_text("登录", exact=True).click()




def login_result(response: dict) -> dict:
    if response.get("result")==0:
        return success_result("成功",response.get("data",{}).get("userDetail"))
    return error_result("登录失败，接口信息异常")
